// import { login, getInfo } from '@/api/user'
import { login } from '@/api/user'
import { setToken, removeToken } from '@/utils/auth'
// import store from '@/store'

const getDefaultState = () => {
  return {
    name: '',
    userId: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, codeImage } = userInfo
    return new Promise((resolve, reject) => {
      login({ param: { userName: username.trim(), password: password, imgCode: codeImage }}).then(response => {
        const { name, avatar } = response
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_USERID', response.record.userId)
        setToken('useLogin', name)
        sessionStorage.setItem('userId', response.record.userId)
        resolve(response)
      }).catch(error => {
        console.log('error', error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    // return new Promise((resolve, reject) => {
    //   getInfo(state.token).then(response => {
    //     const { data } = response

    //     if (!data) {
    //       return reject('Verification failed, please Login again.')
    //     }

    //     const { name, avatar } = data

    //     commit('SET_NAME', name)
    //     commit('SET_AVATAR', avatar)
    //     resolve(data)
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // user logout
  logout({ commit, dispatch, state }) {
    commit('RESET_STATE')
    commit('CHANGE_ROUTES', [])
    dispatch('tagsView/delAllViews', null, { root: true })
    removeToken('useLogin')
    sessionStorage.clear()
    location.reload()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

